﻿namespace BPM.Web.Shared.Interceptor;

public delegate Task HttpClientInterceptorEventHandler(object sender, TokenInterceptorEventArgs e);

/// <summary>
/// Blazor客户端HTTP请求拦截器
/// </summary>
public class TokenInterceptor : TokenInterceptor
{
    /// <summary>
    /// 在HTTP请求发送前
    /// </summary>
    public event EventHandler<TokenInterceptorEventArgs>? BeforeSend;

    /// <summary>
    /// 在HTTP请求发送前
    /// </summary>
    public event HttpClientInterceptorEventHandler? BeforeSendAsync;

    /// <summary>
    /// 在收到HTTP请求的响应后（包括它没有成功）。
    /// </summary>
    public event EventHandler<TokenInterceptorEventArgs>? AfterSend;

    /// <summary>
    /// 在收到HTTP请求的响应后（包括它没有成功）。
    /// </summary>
    public event HttpClientInterceptorEventHandler? AfterSendAsync;

    internal TokenInterceptor()
    {
    }

    internal async Task InvokeBeforeSendAsync(TokenInterceptorEventArgs args)
    {
        BeforeSend?.Invoke(this, args);
        if (BeforeSendAsync != null)
        {
            await InvokeAsync(BeforeSendAsync, args);
        }
    }

    internal async Task InvokeAfterSendAsync(TokenInterceptorEventArgs args)
    {
        AfterSend?.Invoke(this, args);
        if (AfterSendAsync != null)
        {
            await InvokeAsync(AfterSendAsync, args);
        }
    }

    private async Task InvokeAsync(HttpClientInterceptorEventHandler asyncEventHandler, TokenInterceptorEventArgs args)
    {
        if (asyncEventHandler == null)
        {
            return;
        }

        var asyncHandlerTasks = asyncEventHandler
            .GetInvocationList()
            .Cast<HttpClientInterceptorEventHandler>()
            .Select(handler => handler.Invoke(this, args))
            .ToArray();

        await Task.WhenAll(asyncHandlerTasks);
    }
}

